package aqs;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * AQS 测试演示类
 */
public class AQSDemo {
    
    // 共享计数器，用于验证互斥性
    private static final AtomicInteger counter = new AtomicInteger(0);
    
    // 创建我们自定义的互斥锁
    private static final SimpleMutex mutex = new SimpleMutex();
    
    public static void main(String[] args) throws InterruptedException {
        System.out.println("开始 AQS 演示");
        
        // 创建线程池
        ExecutorService executor = Executors.newFixedThreadPool(10);
        
        // 使用 CountDownLatch 等待所有线程执行完成
        CountDownLatch latch = new CountDownLatch(100);
        
        // 提交 100 个任务
        for (int i = 0; i < 100; i++) {
            executor.submit(() -> {
                try {
                    // 使用自定义互斥锁保护共享资源
                    mutex.lock();
                    try {
                        // 模拟一些工作
                        int current = counter.get();
                        Thread.sleep(10); // 增加竞争
                        counter.set(current + 1);
                        System.out.println(Thread.currentThread().getName() + 
                            " - 当前计数: " + counter.get());
                    } finally {
                        mutex.unlock();
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } finally {
                    latch.countDown();
                }
            });
        }
        
        // 等待所有任务完成
        latch.await();
        
        System.out.println("最终计数结果: " + counter.get());
        
        // 测试 tryLock 功能
        testTryLock();
        
        // 关闭线程池
        executor.shutdown();
    }
    
    /**
     * 测试 tryLock 功能
     */
    private static void testTryLock() throws InterruptedException {
        System.out.println("\n开始测试 tryLock 功能");
        
        // 主线程获取锁
        mutex.lock();
        System.out.println("主线程获取了锁");
        
        // 启动一个新线程尝试获取锁
        Thread thread = new Thread(() -> {
            try {
                System.out.println("子线程尝试获取锁(等待1秒)");
                boolean acquired = mutex.tryLock(1, TimeUnit.SECONDS);
                if (acquired) {
                    System.out.println("子线程成功获取了锁");
                    mutex.unlock();
                } else {
                    System.out.println("子线程获取锁超时");
                }
            } catch (InterruptedException e) {
                System.out.println("子线程被中断");
                Thread.currentThread().interrupt();
            }
        });
        
        thread.start();
        
        // 等待一段时间后主线程释放锁
        Thread.sleep(2000);
        System.out.println("主线程释放锁");
        mutex.unlock();
        
        // 等待子线程结束
        thread.join();
        
        System.out.println("tryLock 测试完成");
    }
}
